import pygame
import random

import klocki
import colors

class Klocek:
    def __init__(self):
        """
            state:
                "w" = waiting (next)
                "f" = falling (active)
                "d" = falled (inactive)
        """
        self.state = "w"
        self.klocek = []
        yc = 0
        for y in klocki.rand():
            self.klocek.append([])
            for x in y:
                if x:
                    self.klocek[yc].append(colors.rand())
                else:
                    self.klocek[yc].append(0)
            yc += 1
        self.regenerate()
        self.pos = self.image.get_rect(center=(417,335))

    def regenerate(self):
        self.image = pygame.Surface((len(self.klocek[0])*20,len(self.klocek)*20), pygame.SRCALPHA)
        for y in xrange(len(self.klocek)):
            for x in xrange(len(self.klocek[y])):
                if self.klocek[y][x]:
                    self.image.blit(colors.get(self.klocek[y][x]), (x*20, y*20))
    def rotate(self):
        t = [[0]*len(self.klocek)]*len(self.klocek[0])
        p = []
        for y in t:
            p.append([])
            for x in y:
                p[-1].append(None)
        for y in xrange(len(self.klocek)):
            for x in xrange(len(self.klocek[y])):
                p[x][len(self.klocek) - y - 1] = self.klocek[y][x]
        while self.pos[0] + 20*len(p[0]) > 287:
            self.pos[0] -= 20
        self.klocek = p
        self.regenerate()
        
    def update(self):
        if self.state == "f":
            self.pos[1] += 1
            if self.image.get_rect(topleft=self.pos).bottom > 485:
                self.stop()
                return True
        return False

    def stop(self):
        self.state = 'd'

    def start(self):
        self.pos = [147 - (len(self.klocek[0])-1)/2*20,24]
        self.state = "f"

    def draw(self, dest):
        dest.blit(self.image, self.pos)
